<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Request;
use App\Models\Group;
use Illuminate\Support\Facades\DB;
use App\Models\Role;
use App\Models\UserScore;
use Illuminate\Support\Facades\Log;
use App\Models\Code;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'getLogout']);
//         $this->redirectTo = 'admin/index';
        $this->redirectAfterLogout ="auth/login";
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['username'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
    
    /**
     * @return Ambigous <\Illuminate\Routing\Redirector, \Illuminate\Http\RedirectResponse>
     */
    public function userLogout()
    {
        Auth::logout();
    
        return redirect('/');
    }
    
    /**
     *  企业用户以及个人用户注册
     */
    public function postRegister()
    {
        $registerUser = array();
        $data = Input::only('username','password','repassword','phone_code','user_type');
        
        if(empty(trim($data['username'])))
        {
            return jsonformat('error',trans('auth.name_required'));
        }
        $hasUser = User::where('name','=',$data['username'])->orWhere('phone','=',$data['username'])->orWhere('email','=',$data['username'])->first();
        if( !empty($hasUser) && $hasUser->id > 0 )
        {
            return jsonformat('error',trans('auth.user_exists'));
        }
        if(preg_match(config('app.phone_rule'),$data['username']))
        {
            $registerUser['phone'] = $data['username'];
        }
        elseif (preg_match(config('app.email_rule'),$data['username'] ))
        {
            $registerUser['email'] = $data['username'];
        }
        else
        {
            return jsonformat('error',trans('auth.name_geshi'));
        }
        if(empty(trim($data['password'])))
        {
            return jsonformat('error',trans('auth.pwd_required'));
        }
        if(empty(trim($data['repassword'])))
        {
            return jsonformat('error',trans('auth.repwd_required'));
        }
        if(trim($data['repassword']) !== trim($data['password']))
        {
            return jsonformat('error',trans('auth.pwd_no_match'));
        }
        if(mb_strlen($data['password']) < 6 || mb_strlen($data['password'])>16)
        {
            return jsonformat('error',trans('auth.pwd_length'));
        }
        $nowtime = date('Y-m-d H:i:s');
        $isConti = Code::where('created_at','<',date('Y-m-d H:i:s',time()))
                ->where('created_at','>',date('Y-m-d H:i:s',strtotime("$nowtime - 10 minute")))
                ->where(['phone'=>$data['username'],'code'=>$data['phone_code'],'is_used'=>0])->first();
        if(empty($isConti))
        {
            return jsonformat('error',trans('auth.phone_code'));
        }
        $registerUser['name']  = $data['username'];
        $registerUser['password'] = bcrypt(trim($data['password']));
        if($data['user_type'] == 0)
        {
//            $registerUser['groupid'] = 0;
            DB::beginTransaction();
            try{
                $isConti->update(['is_used'=>1]);
                $newuser =  User::create($registerUser);
                $userRole = Role::where('name','=','user')->first();
                $newuser->attachRole($userRole);
                DB::commit();
                Auth::login($newuser);
            }catch(\PDOException $e){
                Log::info('个人用户注册失败错误 '.$e->getMessage());
                DB::rollBack();
                return jsonformat('error',trans('auth.inte_error'));
            }
			$scoreid = User::where(['name'=>$data['username']])
			           ->first();
		    $socre_new = array(
                    'score' =>  100,
                    'gold'  => 0,
                    'user_id' =>$scoreid->id,
                               );
			UserScore::firstOrCreate($socre_new);           
            return jsonformat('success','恭喜'.$newuser->name.'注册个人用户成功！系统已送您100积分！',$newuser);
        }
        elseif($data['user_type'] == 1)
        {
//             $registerUser['groupid'] = 1;
            DB::beginTransaction();
            try{
                $isConti->update(['is_used'=>1]);
                $newuser =  User::create($registerUser);
                $userRole = Role::where('name','=','company')->first();
                $newuser->attachRole($userRole);
                DB::commit();
                Auth::login($newuser);
            }catch(\PDOException $e){
                Log::info('企业用户注册失败错误 '.$e->getMessage());
                DB::rollBack();
                return jsonformat('error',trans('auth.inte_error'));
            }
            
            return jsonformat('success','恭喜'.$newuser->name.'注册企业用户成功！',$newuser);
        }
    }

    /**
     * 前端用户登陆，包括前台后台。 
     */
    public function postLogin()
    {
        $data=Input::only(['username','password']);
        $user = User::where('name','=',$data['username'])->orWhere('phone','=',$data['username'])->orWhere('email','=',$data['username'])->first();
        if (!empty($user) && count($user) > 0)
        {
            $login = 'name';
            if(preg_match(config('app.phone_rule'),$data['username']))
            {
                $login='phone';
            }
            elseif (preg_match(config('app.email_rule'),$data['username']))
            {
                $login = 'email';
            }
            if (Auth::attempt([$login => $data['username'], 'password' => $data['password']])) {
                $userinfo = User::find(Auth::user()->id);
                $userinfo->last_ip = ip2long(Request::getClientIp());
                $userinfo->last_login_at = $userinfo->fromDateTime($userinfo->freshTimestamp());
                $userinfo->save();
                $userRoles = array_fetch($userinfo->roles->toArray(),'id');
                $group_id = DB::table('group_role')->whereIn('role_id',$userRoles)->lists('group_id');
                $usergroups = Group::whereIn('id',$group_id)->first();
                $userinfo->group_id = $usergroups->id;
                if(empty($usergroups))
                {
                    Auth::logout();
                    return jsonformat('error',trans('auth.user_param_error'));
                }
                return jsonformat('success','恭喜您，'.$userinfo->name.'登陆成功！',$userinfo);
            }
            else
            {
                return jsonformat('error',trans('auth.no_match'));
            }
        }
        else
        {
            return jsonformat('error',trans('auth.nouser'));
        }
    }
    
    /**
     * 后台登陆
     */
    public function authenticate()
    {
        $data=Input::only(['username','password']);
        $user = User::where(array('name'=>$data['username']))->first();
        if(empty($user)){
            return redirect()->intended('auth/login')
            ->withErrors(['username' =>  Lang::get('auth.nouser')]);
        }
        $userGroup =Group::where('name','=','admin')->first();
        $adminRoles = array_fetch($userGroup->group_roles->toArray(),'name');
        if($user->hasRole($adminRoles)){
            if (Auth::attempt(['name' => $data['username'], 'password' => $data['password']])) {
                $userinfo = User::find(Auth::user()->id);
                $userinfo->last_ip = ip2long(Request::getClientIp());
                $userinfo->last_login_at = $userinfo->fromDateTime($userinfo->freshTimestamp());
                $userinfo->save();
                return redirect()->intended('/admin/index');
            }
            else 
            {
                return redirect()->intended('auth/login')
                ->withErrors(['username' => $this->getFailedLoginMessage()]);
            }
        }
        else
        {
            return redirect()->intended('auth/login')
                ->withErrors(['username' =>  Lang::get('auth.nopermission')]);
        }
    }
}
